// src/main/services/window-service.ts
import { BrowserWindow, BrowserWindowConstructorOptions, globalShortcut, ipcMain, shell, Menu, MenuItemConstructorOptions, screen } from 'electron';
import { join } from 'path';
import { v4 as uuid } from 'uuid';
import icon from '../resources/icon.png?asset'
import { createdWindowConfig } from './config';
import { logger } from '@sentry/electron/main';
import { session } from 'electron';

// ==================== 类型定义 ====================
export interface WindowOptions {
  width?: number;
  height?: number;
  url?: string;
  title?: string;
  resizable?: boolean;
  minimizable?: boolean;
  maximizable?: boolean;
  closable?: boolean;
  backgroundColor?: string;
  show?: boolean;
  icon?: string;
  webPreferences?: BrowserWindowConstructorOptions['webPreferences'];
  // 悬浮窗特有选项
  draggable?: boolean;
  hasShadow?: boolean;
  contextMenu?: MenuItemConstructorOptions[];
  imageUrl?: string; // 悬浮窗图片URL
}

export interface ModalOptions extends WindowOptions {
  parentId?: string; // 使用 UUID 替代数字 ID
}

export interface WindowResult {
  success: boolean;
  windowId?: string;
  error?: string;
}

// ==================== 服务实现 ====================
export class WindowService {


  private windows = new Map<string, BrowserWindow>();
  private pendingWindows = new Set<string>();

  /**
   * 创建新窗口（带唯一ID标识）
   */
  public async createWindow(options: WindowOptions = {}): Promise<WindowResult> {
    const windowId = uuid();
    this.pendingWindows.add(windowId);

    session.defaultSession.webRequest.onBeforeSendHeaders((details, callback) => {
      details.requestHeaders['Cache-Control'] = 'no-cache';
      details.requestHeaders['Pragma'] = 'no-cache';
      callback({ cancel: false, requestHeaders: details.requestHeaders });
    });


    try {
      const window = this.initializeWindow(windowId, options);

      await this.loadContent(window, options.url);

      this.windows.set(windowId, window);

      globalShortcut.register('CommandOrControl+Shift+1', function () {
        window.webContents.openDevTools()
      })

      return { success: true, windowId };
    } catch (error) {
      return {
        success: false,
        error: error instanceof Error ? error.message : 'Unknown error'
      };
    } finally {
      this.pendingWindows.delete(windowId);
    }
  }

  /**
   * 创建模态窗口
   */
  public async createModalWindow(options: ModalOptions): Promise<WindowResult> {
    const parent = options.parentId ? this.windows.get(options.parentId) : undefined;
    if (options.parentId && !parent) {
      return { success: false, error: `Parent window ${options.parentId} not found` };
    }

    return this.createWindow({
      ...options,
    });
  }

  /**
 * 创建悬浮窗
 */
  public async createFloatWindow(options: WindowOptions = {}): Promise<WindowResult> {
    const windowId = uuid();
    this.pendingWindows.add(windowId);

    try {
      const defaultFloatOptions: BrowserWindowConstructorOptions = {
        width: options.width || 120,
        height: options.height || 120,
        type: 'toolbar',
        frame: false,
        resizable: false,
        transparent: true,
        alwaysOnTop: true,
        webPreferences: {
          preload: join(__dirname, '../preload/index.js'),
          nodeIntegration: false,
          contextIsolation: true,
          ...options.webPreferences
        },
        ...options,
      };

      const window = new BrowserWindow(defaultFloatOptions);

      // 设置初始位置（右下角）
      const { width, height } = screen.getPrimaryDisplay().workAreaSize;
      const initialPosition = {
        x: width - (options.width || defaultFloatOptions.width || 0) - 40,
        y: height - (options.height || defaultFloatOptions.height || 0) - 40
      };
      window.setPosition(initialPosition.x, initialPosition.y);

      // 设置窗口事件
      this.setupWindowEvents(windowId, window);



      // 注册拖拽IPC通信
      const dragStartHandler = (_: any, { x, y }: any) => {
        if (window && !window.isDestroyed()) {
          window.setIgnoreMouseEvents(false);
        }
      };

      const draggingHandler = (_: any, { x, y }: any) => {
        if (window && !window.isDestroyed()) {
          const [currentX, currentY] = window.getPosition();
          // 取正数
          window.setPosition(currentX + x, currentY + y);
        }
      };

      // 为每个窗口注册特定的IPC处理程序
      const specificDragStartHandler = (_: any, data: any) => {
        logger.info(`Specific drag start request received for window ${windowId}`);
        dragStartHandler(_, data);
      };

      const specificDraggingHandler = (_: any, data: any) => {
        console.log(`Specific dragging request received for window ${windowId} ${JSON.stringify(data)}`);

        draggingHandler(_, data);
      };

      // 监听来自渲染进程的拖拽请求
      const dragStartRequestHandler = (_: any, data: any) => {
        logger.info(`Drag start request received for window ${windowId}`);
        if (data.windowId === windowId) {
          dragStartHandler(_, data);
        }
      };

      const dragMoveRequestHandler = (_: any, data: any) => {
        logger.info(`Dragging request received for window ${windowId}`);
        if (data.windowId === windowId) {
          draggingHandler(_, data);
        }
      };

      ipcMain.handle(`float-window-drag-start:${windowId}`, specificDragStartHandler);
      ipcMain.handle(`float-window-dragging:${windowId}`, specificDraggingHandler);
      ipcMain.on('float-window-drag-start-request', dragStartRequestHandler);
      ipcMain.on('float-window-drag-move-request', dragMoveRequestHandler);

      // 在窗口关闭时清理事件监听器
      window.on('closed', () => {
        ipcMain.removeHandler(`float-window-drag-start:${windowId}`);
        ipcMain.removeHandler(`float-window-dragging:${windowId}`);
        ipcMain.removeListener('float-window-drag-start-request', dragStartRequestHandler);
        ipcMain.removeListener('float-window-drag-move-request', dragMoveRequestHandler);
      });

      if (options.url) {
        await this.loadContent(window, options.url + '?windowId=' + windowId + '&t=' + Date.now());
      } else if (options.imageUrl) {
        // 如果提供了图片URL，则创建一个显示该图片的简单页面
        const htmlContent = `
        <!DOCTYPE html>
        <html style="height: 100%; margin: 0;">
        <head>
          <meta charset="UTF-8">
          <style>
            body {
              margin: 0;
              padding: 0;
              overflow: hidden;
              background: transparent;
              display: flex;
              justify-content: center;
              align-items: center;
              height: 100%;
            }
            img {
              max-width: 100%;
              max-height: 100%;
              pointer-events: none;
              user-select: none;
            }
          </style>
        </head>
        <body>
          <img src="${options.imageUrl}" draggable="false" />
        </body>
        </html>`;
        await window.loadURL(`data:text/html;charset=UTF-8,${encodeURIComponent(htmlContent)}`);
      }

      this.windows.set(windowId, window);

      return { success: true, windowId };
    } catch (error) {
      return {
        success: false,
        error: error instanceof Error ? error.message : 'Unknown error'
      };
    } finally {
      this.pendingWindows.delete(windowId);
    }
  }

  /**
   * 安全获取窗口实例
   */
  public getWindow(windowId: string): BrowserWindow | undefined {
    return this.windows.get(windowId);
  }

  /**
   * 关闭所有窗口
   */
  public closeAllWindows() {
    this.windows.forEach(window => {
      if (!window.isDestroyed()) window.close();
    });
    this.windows.clear();
  }

  // ================ 私有方法 ================
  private initializeWindow(windowId: string, options: WindowOptions): BrowserWindow {
    const window = new BrowserWindow(createdWindowConfig);

    this.setupWindowEvents(windowId, window);
    return window;
  }


  private setupWindowEvents(windowId: string, window: BrowserWindow) {
    window.on('ready-to-show', () => window.show());

    window.on('closed', () => {
      this.windows.delete(windowId);
    });

    // 安全处理外部链接
    window.webContents.setWindowOpenHandler(({ url }) => {
      if (!url.startsWith('http')) return { action: 'deny' };
      shell.openExternal(url);
      return { action: 'deny' };
    });

    // 开发工具自动打开
    if (process.env.NODE_ENV === 'development') {
      // window.webContents.on('did-frame-finish-load', () => {
      //   window.webContents.openDevTools({ mode: 'detach' });
      // });
    }
  }

  private initializeFloatWindow(windowId: string, options: BrowserWindowConstructorOptions): BrowserWindow {
    const window = new BrowserWindow({
      ...createdWindowConfig,
      ...options
    })
    this.setupWindowEvents(windowId, window);
    return window;
  }

  private async loadContent(window: BrowserWindow, url?: string) {
    if (!url) return;

    try {
      url.startsWith('http')
        ? await window.loadURL(url, { extraHeaders: 'pragma: no-cache\nCache-Control: no-cache' })
        : await window.loadFile(url);
    } catch (error) {
      console.error('Window load error:', error);
      await window.loadFile(join(__dirname, '../../renderer/fallback.html'));
    }
  }
}

// ==================== IPC 安全暴露 ====================
export function registerWindowIPC(service: WindowService) {
  // 创建普通窗口
  ipcMain.handle('window:create', (_, options: WindowOptions) =>
    service.createWindow(options)
  );

  // 创建模态窗口
  ipcMain.handle('window:create-modal', (_, options: ModalOptions) =>
    service.createModalWindow(options)
  );

  // 窗口控制方法
  ipcMain.handle('window:close', (_, windowId: string) => {
    service.getWindow(windowId)?.close();
  });

  // 创建悬浮窗
  ipcMain.handle('window:create-float', (_, options: WindowOptions) =>
    service.createFloatWindow(options)
  );

  ipcMain.handle('window:minimize', (_, windowId: string) => {
    service.getWindow(windowId)?.minimize();
  });

  ipcMain.handle('window:maximize', (_, windowId: string) => {
    const win = service.getWindow(windowId);
    win?.isMaximized() ? win.unmaximize() : win?.maximize();
  });

  ipcMain.handle('window:reload', (_, windowId: string) => {
    try {
      const win = service.getWindow(windowId);
      win?.reload();
      return { success: true, windowId };
    } catch (error) {
      return {
        success: false,
        error: error instanceof Error ? error.message : 'Unknown error'
      };
    }
  });

  // 应用退出时清理
  ipcMain.on('app:quit', () => service.closeAllWindows());
}

// ==================== 单例导出 ====================
export const windowService = new WindowService();

// 主进程初始化调用：
// registerWindowIPC(windowService);